from django.http import Http404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template import Context, loader
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.shortcuts import get_object_or_404, render_to_response
from django.core.urlresolvers import reverse
from polls.models import Choice, Poll, Vote
from finance.models import Account

def detail(request, poll_id):
  poll = get_object_or_404(Poll, pk=poll_id)
  balance = Account.objects.get(user=request.user).balance
  return render_to_response('polls/detail.html', {
      'user': request.user,
      'balance': balance,
      'poll': poll,
  }, context_instance=RequestContext(request))

def get_balance(user):
  account = Account.objects.get(user=request.user)
  return account.balance

def vote(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = poll.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render_to_response('polls/detail.html', {
            'poll': poll,
            'error_message': "You didn't select a choice.",
        }, context_instance=RequestContext(request))
    else:
        # TODO(yueqi): check if it's a valid bet.
        import decimal
        amount = decimal.Decimal(request.POST['amount'])
        # Update user's account balance
        account = Account.objects.get(user=request.user)
        if account.balance >= amount:
          account.balance -= amount
          account.save()

        # Update choice
        selected_choice.votes += 1
        selected_choice.save()

        # Record every vote transaction.
        vote = Vote()
        vote.choice = selected_choice
        vote.user = request.user
        vote.amount = amount
        vote.save()


    # Always return an HttpResponseRedirect after successfully dealing
    # with POST data. This prevents data from being posted twice if a
    # user hits the Back button.
    return HttpResponseRedirect(reverse('poll_results', args=(poll.id,)))
